package com.kykj.kykj.config;

import com.kykj.kykj.service.impl.RouteServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component //注入Spring
public class WebInterceptor implements HandlerInterceptor {
    @Resource
    RouteServiceImpl routeService;
    //访问controller之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //设置跨域请求头
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", request.getMethod());
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        String uname =request.getHeader("uname");//获取参数
        ServletOutputStream servletOutputStream = response.getOutputStream();//输出对象
        if(routeService.isRoute(uname, request.getRequestURI())){
            return true;//允许通过
        }else{
            servletOutputStream.write("{\"code\":-9999,\"msg\":\"权限不足！\"}".getBytes());
            return false;//通过拦截器
        }

    }
    //访问controller之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
        System.out.println("拦截器postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求处理完成后
        System.out.println("拦截器afterCompletion");
    }
}
